import router from ".";
import userStore from '@/store/userStore'
import store from "@/store";
import {message} from 'element-ui'

let getRouter
//路由白名单
// const whiteList = ['/','','/login','home','goods_manager','goods_manager/goodsInbounch','goods_manager/codedIntoStorage','goods_manager/productDisassembly','goods_manager/returnGoods','goods_manager/inventoryStatistics','goods_manager/storesAllocate','goods_manager/purchaseReturnsOrders','goods_manager/doosView']

const whiteList = ['/login'];

router.beforeEach((to,from,next) => {
  //是否登录
  if(userStore.state.token){
    //访问的是否是登录页
    if(to.path !== '/login'){
      //已经获取了动态路由
      // console.log(userStore.state.initRoutes);
      if(userStore.state.initRoutes.length > 0){
        next();
      }else{
        gotoRouter(to,next)
      }
    }else{
      message.error('您已经登录')
      next('/')
    }
  }else{
    //访问的是否为白名单
    if(whiteList.indexOf(to.path) !== -1){
      next()
    }else{
      next('/login')
    }
  }
})

//处理动态路由
function gotoRouter(to,next){
  getRouter = userStore.state.routes;
  //过滤路由
  getRouter = filterAsyncRouter(getRouter)
  getRouter.push({path:'*',name:'404',component:() => import(`@/views/404View.vue`)})
  //更新store
  store.commit('userStore/setInitRoutes',getRouter)
  //添加路由 
  router.addRoutes(getRouter)
  // console.log(router.options);
  next({...to,replace:true})
}

//递归过滤路由
function filterAsyncRouter(asyncRouterMap){
  const  accessedRouters = [];
  try{
    asyncRouterMap.forEach(item => {
      let new_item ={
        path:item.url,
        name:item.name,
        component: () => item.component === 'DashBoard' ? import(`@/views/DashBoard`) : import(`@/views/aside/${item.component}`)
      }
      if(item.children && item.children.length){
        const children = filterAsyncRouter(item.children)
        new_item = {...new_item,children}
      }
      if(item.redirect){
        new_item = {...new_item,redirect:item.redirect}
      }
      if(item.icon !== '' && item.title !== ''){
        new_item = {...new_item, meta: { title: item.title, icon: item.icon }}
      }else if(item.title !== '' && item.icon === ''){
        new_item = { ...new_item, meta: { title: item.title } }
      }
      accessedRouters.push(new_item)
    })
  }catch (error){
    console.error(error)
    return [] 
  }
  return accessedRouters
}